import os
from hashlib import pbkdf2_hmac

from db_base import DatabaseManager, dbconfig


class UserManager:
    def __init__(self):
        # 应该实例化DatabaseManager，而不是直接引用类
        self.db_manager = DatabaseManager(dbconfig)

    def __del__(self):
        # 确保数据库连接被关闭
        self.db_manager.close()

    def register_user(self, username, password, role):
        """注册新用户"""
        if self.user_exists(username):
            raise ValueError("用户名已存在")
        salt = os.urandom(32)
        hashed_pw = pbkdf2_hmac('sha256', password.encode(), salt, 100000).hex()
        query = """
        INSERT INTO users 
        (username, password_salt, password_hash, role, account_status)
        VALUES (%s, %s, %s, %s, 'active')
        """
        try:
            self.db_manager.execute_query(query, (username, salt.hex(), hashed_pw, role), commit=True)
            return True
        except Exception as e:
            print(f"注册用户失败: {e}")
            return False

    def verify_user(self, username, password):
        """验证用户凭据"""
        query = """
        SELECT * FROM users 
        WHERE username = %s 
        AND account_status = 'active'
        """
        user = self.db_manager.execute_query(query, (username,))
        if not user:
            return False
        user = user[0]  # 取出用户信息
        salt = bytes.fromhex(user['password_salt'])
        stored_hash = user['password_hash']
        new_hash = pbkdf2_hmac('sha256', password.encode(), salt, 100000).hex()
        if new_hash == stored_hash:
            update_query = """
            UPDATE users 
            SET last_login = NOW() 
            WHERE user_id = %s
            """
            self.db_manager.execute_query(update_query, (user['user_id'],), commit=True)
            return user  # 返回完整用户对象
        return False

    def change_password(self, username, old_password, new_password):
        """更改用户密码"""
        user = self.verify_user(username, old_password)
        if not user:
            return False
        salt = os.urandom(32)
        new_hash = pbkdf2_hmac('sha256', new_password.encode(), salt, 100000).hex()
        query = """
        UPDATE users 
        SET password_salt = %s, password_hash = %s 
        WHERE user_id = %s
        """
        try:
            self.db_manager.execute_query(query, (salt.hex(), new_hash, user['user_id']), commit=True)
            return True
        except Exception as e:
            print(f"更改密码失败: {e}")
            return False

    def user_exists(self, username):
        """检查用户名是否存在"""
        query = "SELECT COUNT(*) AS count FROM users WHERE username = %s"
        result = self.db_manager.execute_query(query, (username,))
        return result[0]['count'] > 0 if result else False

    def get_user_info(self, username):
        """获取用户信息（包括关联的患者信息）"""
        query = """
        SELECT 
            users.user_id,
            users.username,
            users.role,
            patient_profiles.full_name 
        FROM users 
        LEFT JOIN patient_profiles 
            ON users.user_id = patient_profiles.user_id
        WHERE users.username = %s
        """
        result = self.db_manager.execute_query(query, (username,))
        return result[0] if result else None

    def deactivate_user(self, username):
        """
        停用用户账户 (UserManager 类中的实现)
        返回:
            bool: 是否成功执行
        """
        query = """
        UPDATE users 
        SET account_status = 'disabled' 
        WHERE username = %s
        """
        result = self.db_manager.execute_query(query, (username,), commit=True)
        return result.rowcount > 0  # 返回是否影响了行

    def is_therapist(self, therapist_id):
        """
        验证用户是否为治疗师
        参数:
            user_id: 用户ID
        返回:
            bool: 是否是治疗师
        """
        try:
            # 查询用户角色
            query = "SELECT role FROM users WHERE user_id = %s"
            result = self.db_manager.execute_query(query, (therapist_id,))
            if not result:
                return False  # 用户不存在
            user_role = result[0].get('role')
            return user_role == 'therapist'
        except Exception as e:
            print(f"验证治疗师权限失败: {e}")
            return False  # 异常时默认返回无权限
